package com.glory.brepda.activity.mfg;


import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Build;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.EdcSetBinAdapter;
import com.glory.brepda.adapter.LastBatchAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.entity.BinInfoEntity;
import com.glory.brepda.entity.EdcEntity;
import com.glory.brepda.entity.EdcSetBinEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class FTOffLineDataSortActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.tvScarpNum)
    TextView tvScarpNum;
    @BindView(R.id.tvTotal)
    TextView tvTotal;
    @BindView(R.id.tvGetData)
    TextView tvGetData;
    @BindView(R.id.rvBINInfoList)
    RecyclerView rvBINInfoList;
    @BindView(R.id.rvLastBatchList)
    RecyclerView rvLastBatchList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private EdcSetBinAdapter edcSetBinAdapter;
    private EdcEntity body;
    private LastBatchAdapter lastBatchAdapter;
    private ArrayList<EdcEntity.EdcSet> edcList = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_ft_off_line_data_sort;
    }

    @Override
    protected void initView() {
        initRecyclerView(rvBINInfoList,this);
        initRecyclerView(rvLastBatchList,this);
        tvTitle.setText("离线整合");
        setMainLayout(llMain);
        edcSetBinAdapter = new EdcSetBinAdapter(null);
        edcSetBinAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        edcSetBinAdapter.isFirstOnly(false);
        rvBINInfoList.setAdapter(edcSetBinAdapter);
        lastBatchAdapter = new LastBatchAdapter(null);
        lastBatchAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        lastBatchAdapter.isFirstOnly(false);
        rvLastBatchList.setAdapter(lastBatchAdapter);
        initEdit(etLot, s -> LotUtils.searchLotInfo(FTOffLineDataSortActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                tvNum.setText(response.getLOT().getMAINQTY());
                edcSetBinAdapter.setMainqty(Integer.parseInt(response.getLOT().getMAINQTY()));
                requestEdcData();
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t,"LOTQUERY");
            }
        }));

    }

    private void requestEdcData() {
//        String ss = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"\",\"RESULT\":\"SUCCESS\"},\"Body\":{\"LOTID\":\"20G2589-1-012\",\"PARTNAME\":\"FN62301\",\"STEPNAME\":\"T1110\",\"EDCSETLIST\":[{\"EDCSETNAME\":\"836_BIN1-8\",\"EDCSETDESCRIPTION\":\"836_BIN1-8\",\"EDCTYPE\":\"BIN\",\"EDCSETBINLINELIST\":[{\"NAME\":\"BIN1\",\"DESCRIPTION\":\"良品\",\"SPECTYPE\":\"PERCENT\",\"LSL\":\"98.00\",\"BINTYPE\":\"P\",\"ACTIONPARAM1\":\"A\",\"BINACTION\":\"Split\"},{\"NAME\":\"BIN2\",\"DESCRIPTION\":\"OS不良品\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN3\",\"DESCRIPTION\":\"FT不良品\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.40\",\"BINTYPE\":\"F\",\"BINGROUP\":\"BIN3_4_5\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN4\",\"DESCRIPTION\":\"FT不良品\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"1.50\",\"BINTYPE\":\"F\",\"BINGROUP\":\"BIN3_4_5\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN5\",\"DESCRIPTION\":\"FT不良品\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.30\",\"BINTYPE\":\"F\",\"BINGROUP\":\"BIN3_4_5\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN6\",\"DESCRIPTION\":\"QA不良品\",\"USL\":\"0.00\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN7\",\"DESCRIPTION\":\"印字不良\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN8\",\"DESCRIPTION\":\"引脚不良\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN9\",\"DESCRIPTION\":\"少数（虚拟BIN）\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN10\",\"DESCRIPTION\":\"报废（虚拟BIN）\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN11\",\"DESCRIPTION\":\"样品\",\"BINTYPE\":\"P\",\"BINACTION\":\"Split\"},{\"NAME\":\"BIN12\",\"DESCRIPTION\":\"未测BIN\",\"BINTYPE\":\"P\",\"BINACTION\":\"Split\"},{\"NAME\":\"BIN3_4_5\",\"DESCRIPTION\":\"FT不良BIN组\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"2.0\",\"BINTYPE\":\"G\",\"BINACTION\":\"None\"},{\"NAME\":\"BIN13\",\"DESCRIPTION\":\"掉料(虚拟BIN)\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN99\",\"SPECTYPE\":\"PERCENT\",\"BINTYPE\":\"O\",\"BINACTION\":\"None\"}]}]}}}";
//        BaseResponseBean<EdcEntity> dd = (new Gson()).fromJson(ss, new TypeToken<BaseResponseBean<EdcEntity>>() {
//        }.getType());
//        if (dd.isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
//            body = dd.getResponse().getBody();
//            if (body.getEDCSETLIST().get(0).getEDCTYPE().equals("BIN")){
//                edcSetBinAdapter.setNewData(body.getEDCSETLIST().get(0).getEDCSETITEMLINELIST());
//            }else {
//                showConfirmDialog(FTOffLineDataSortActivity.this,"只支持BIN数据类型采集");
//            }
//        }
        FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                (new TypeToken<BaseResponseBean<EdcEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    body = response.body().getResponse().getBody();
                    edcList.addAll(body.getEDCSETLIST());
                    lastBatchAdapter.setNewData(body.getLOTLIST());
                    tvScarpNum.setText(String.valueOf(body.getDAWBQTY()));
                    tvTotal.setText(String.valueOf(body.getTOTALQTY()));
                    if (body.getEDCSETLIST().size() <= 0){
                        showToast("BIN列表为空",false);
                        return;
                    }

                    if (body.getEDCSETLIST().get(0).getEDCTYPE().equals("BIN")){
                        List<EdcSetBinEntity> binData = new ArrayList<>();
                        for (EdcSetBinEntity entity : body.getEDCSETLIST().get(0).getEDCSETBINLINELIST()){
                            if (entity.getBINTYPE().equals("G")){
                                continue;
                            }

                            binData.add(entity);
                        }
                        edcSetBinAdapter.setNewData(binData);
                    }else {
                        showConfirmDialog(FTOffLineDataSortActivity.this,"只支持BIN数据类型采集");
                    }
//                    getData();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"CPCGETEDCCURRENT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("LOTID",getText(etLot));
        NetUtils.requestPostNet("IF.EDCCURRENT","Common",FTOffLineDataSortActivity.this,map,callBack);
    }

    private void getData() {
        FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                (new TypeToken<BaseResponseBean<EdcEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    if (response.body().getResponse().getBody().getEDCSETLIST().size() <= 0){
                        showConfirmDialog("暂无数据");
                        return;
                    }
                    EdcEntity mBody = response.body().getResponse().getBody();
                    if (mBody.getEDCSETLIST().get(0).getEDCTYPE().equals("BIN")){
                        List<EdcSetBinEntity> binData = new ArrayList<>();
                        for (EdcSetBinEntity entity : mBody.getEDCSETLIST().get(0).getEDCSETBINLINELIST()){
                            if (entity.getBINTYPE().equals("G")){
                                continue;
                            }

                            binData.add(entity);
                        }
                        edcSetBinAdapter.setNewData(binData);
                    }else {
                        showConfirmDialog(FTOffLineDataSortActivity.this,"只支持BIN数据类型采集");
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "RTM.BINRESULTREQUEST");
            }
        };

        JsonObject map = new JsonObject();
//                map.addProperty("EQUIPMENTID",getText(etEqpWork));
        map.addProperty("LOTID",getText(etLot));
        map.add("EDCSETLIST", new JsonParser().parse(new Gson().toJson(edcList)).getAsJsonArray());
        NetUtils.requestPostNet("RTM.BINRESULTREQUEST","BINRESULTREQUEST",FTOffLineDataSortActivity.this,map,callBack);

    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvTempSave,R.id.tvSave,R.id.tvGetData,R.id.tvBaseSubmit,R.id.tvData})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvTempSave:
                submit(true);
                break;
            case R.id.tvSave:
            case R.id.tvBaseSubmit:

                if (getText(etLot).equals("")){
                    showToast("请扫描Lot信息",false);
                    return;
                }

                if (edcSetBinAdapter.getData() == null){
                    showToast("暂无BIN数据",false);
                    return;
                }

                int sum = 0;
                for (EdcSetBinEntity entity : edcSetBinAdapter.getData()){
                    sum += entity.getVALUE();
                }

                int lotNum = Integer.parseInt(tvTotal.getText().toString());
                if (lastBatchAdapter.getData().size() > 0) {
                    for (EdcEntity.EdcSet edcSet : lastBatchAdapter.getData()) {
                        if (edcSet.getSUBQTY() != 1){
                            lotNum -= Integer.parseInt(edcSet.getMAINQTY());
                        }

                    }
                }

                if (sum != lotNum){
                    showConfirmDialog("Total不等于BIN的总数！差值：" + (lotNum - sum));
                    return;
                }

                submit(false);
                break;
            case R.id.tvGetData:
                for (EdcSetBinEntity entity : edcSetBinAdapter.getData()){
                    if (entity.getNAME().equals("BIN99")){
                        synchronous(edcSetBinAdapter.getData().indexOf(entity));
                        return;
                    }
                }
                showToast("未找到BIN99，无法同步",false);
                break;
            case R.id.tvData:
                if (getText(etLot).equals("")){
                    showToast("批次ID不能为空",false);
                    return;
                }

                FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                        (new TypeToken<BaseResponseBean<EdcEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            if (response.body().getResponse().getBody().getEDCSETLIST().size() <= 0){
                                showConfirmDialog("暂无数据");
                                return;
                            }
                            EdcEntity mBody = response.body().getResponse().getBody();
                            if (mBody.getEDCSETLIST().get(0).getEDCTYPE().equals("BIN")){
                                List<EdcSetBinEntity> binData = new ArrayList<>();
                                for (EdcSetBinEntity entity : mBody.getEDCSETLIST().get(0).getEDCSETBINLINELIST()){
                                    if (entity.getBINTYPE().equals("G")){
                                        continue;
                                    }

                                    binData.add(entity);
                                }
                                edcSetBinAdapter.setNewData(binData);
                            }else {
                                showConfirmDialog(FTOffLineDataSortActivity.this,"只支持BIN数据类型采集");
                            }
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "RTM.BINRESULTREQUEST");
                    }
                };

                JsonObject map = new JsonObject();
//                map.addProperty("EQUIPMENTID",getText(etEqpWork));
                map.addProperty("LOTID",getText(etLot));
                map.add("EDCSETLIST", new JsonParser().parse(new Gson().toJson(edcList)).getAsJsonArray());
                NetUtils.requestPostNet("RTM.BINRESULTREQUEST","BINRESULTREQUEST",FTOffLineDataSortActivity.this,map,callBack);
                break;
        }
    }

    private void synchronous(int position) {
        List<EdcSetBinEntity> data = edcSetBinAdapter.getData();
        //修改BIN2得数量
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getNAME().equals("BIN2")){
                EdcSetBinEntity entity = data.get(i);
                int value = entity.getVALUE();
                entity.setVALUE(value - body.getDAWBQTY());
                edcSetBinAdapter.notifyItemChanged(i);
                break;
            }
        }
        //修改BIN99得数量
        edcSetBinAdapter.getData().get(position).setVALUE(body.getDAWBQTY());
        edcSetBinAdapter.notifyItemChanged(position);
        showToast("同步成功",true);
        tvGetData.setVisibility(View.GONE);
    }

    private void submit(boolean isTemp) {

        showSubmitDialog(new onSubmitListener() {
            @Override
            public void setOnSubmitListener() {

                FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                        (new TypeToken<BaseResponseBean<EdcEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                            String ruleMsg = "";
                            if (response.body().getResponse().getBody()!= null && response.body().getResponse().getBody().getRuleMsg().equals("低良进待决")){
                                ruleMsg = ",低良进待决";
                            }
                            showConfirmDialog(FTOffLineDataSortActivity.this,"提交成功" + ruleMsg);
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(),"CPCGETEDCCURRENT");
                    }
                };

                JsonObject map = new JsonObject();
                map.addProperty("LOTID",getText(etLot));
                map.addProperty("ISTEMP",isTemp);
                map.addProperty("ISRMS",false);
                map.addProperty("TOTALQTY",tvTotal.getText().toString());
//                        JsonObject js1 = new JsonObject();
//                        js1.add("EDCSETBINLINE",new JsonParser().parse(new Gson().toJson(edcSetBinAdapter.getData())).getAsJsonArray());
//                        JsonObject js2 = new JsonObject();
//                        js2.add("EDCSETBINLINELIST",js1);
//                        js2.addProperty("EDCSETNAME",body.getEDCSETLIST().get(0).getEDCSETNAME());
//                        js2.addProperty("EDCSETDESCRIPTION",body.getEDCSETLIST().get(0).getEDCSETDESCRIPTION());
//                        js2.addProperty("EDCTYPE",body.getEDCSETLIST().get(0).getEDCTYPE());
//                        JsonObject js3 = new JsonObject();
//                        js3.add("EDCSET",js2);
//                        map.add("EDCSETLIST", js3);
                List<EdcSetBinEntity> data = edcSetBinAdapter.getData();
                List<EdcEntity.EdcSet> edcsetlist = body.getEDCSETLIST();
                edcsetlist.get(0).setEDCSETBINLINELIST(edcSetBinAdapter.getData());
                map.add("EDCSETLIST",new JsonParser().parse(new Gson().toJson(edcsetlist)).getAsJsonArray());
                NetUtils.requestPostNet("IF.SAVEEDCDATA","DataIntegrationFt",FTOffLineDataSortActivity.this,map,callBack);
            }
        });
    }

}